package com.boarsoft.boar.deploy.lib.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.BaseConfig;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.deploy.entity.LibDeployInfo;
import com.boarsoft.boar.dir.DirBiz;
import com.boarsoft.boar.dir.bean.DirTreeNode;
import com.boarsoft.boar.entity.DirInfo;
import com.boarsoft.boar.entity.LibInfo;
import com.boarsoft.boar.lib.action.LibAction;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.JsonUtil;

@RestController
@RequestMapping("/lib")
public class LibDeployAction extends LibAction {
	private static final Logger log = LoggerFactory.getLogger(LibDeployAction.class);

	@Autowired
	private DirBiz dirBiz;

	@RequestMapping("/save.do")
	@Authorized(code = "lib.save")
	public ReplyInfo<Object> save(String parentId, LibDeployInfo c) {
		ReplyInfo<Object> ro;
		DirInfo d;
		if (Util.strIsEmpty(c.getId())) {
			// 检查parent是否存在，取出path拼接
			d = new DirInfo();
			if (Util.strIsEmpty(parentId)) {
				// 请求参数中没有parent，则手动指定目录为根目录
				parentId = BaseConfig.DIR_ROOT;// added by Oscar zhou 20160921
				log.info("新建库包时没有上送parent，设置该库包的默认parent为root");
			}

			d.setParentId(parentId);
			// 设置这个目录在目录树上的路径
			if (BaseConfig.DIR_ROOT.equals(parentId)) {
				d.setPath("/");
				d.setLevel(1);
			} else {
				DirInfo p = dirBiz.get(parentId);
				d.setLevel(p.getLevel() + 1);
				d.setPath(String.format("%s/%s", p.getPath(), p.getId()));
			}
			d.setType(DirInfo.TYPE_LIB);
			c.setStatus(LibInfo.STATUS_INUSE);// 应用默认为启用

			String projId = dirBiz.lookup(d, DirInfo.TYPE_PROJ);
			if (projId == null) {
				return new ReplyInfo<Object>(Constants.ERROR_NOTFOUND, "Msg.common.project");
			}
			c.setProjId(projId);
			ro = libBiz.add(d, c);
		} else {
			d = dirBiz.get(c.getId());
		}
		ro = libBiz.update(d, c);
		if (ro.isSuccess()) {
			DirTreeNode dtn = new DirTreeNode((DirInfo) ro.getData());
			return new ReplyInfo<Object>(true, dtn);
		}
		return new ReplyInfo<Object>(ro.getData());
	}

	@RequestMapping("/get.do")
	@Authorized(code = "lib.get")
	public ReplyInfo<Object> get(String id) {
		LibInfo o = libBiz.get(id);
		return new ReplyInfo<Object>(true, JsonUtil.from(o, "apps"));
	}
}